//新消息通知

var message = {
		time: 0,  
        title: document.title,  
        timer: null,  
		show: function () {  
                var title = message.title.replace("【　　　】", "").replace("【新消息】", "");  
                // 定时器，设置消息切换频率闪烁效果就此产生  
                message.timer = setTimeout(function () {  
                    message.time++;  
                    message.show();  
                    if (message.time % 2 == 0) {  
                        document.title = "【新消息】" + title  
                    }  
  
                    else {  
                        document.title = "【　　　】" + title  
                    };  
                }, 300);  
                return [message.timer, message.title];
		},
		 clear: function () {  
                clearTimeout(message.timer);  
                document.title = message.title;  
            }  
};
		
//窗口缩放
     window.getHeight= function(){  
        if(window.innerHeight!= undefined){  
            return window.innerHeight;  
        }  
        else{  
            var B= document.body, D= document.documentElement;  
            return Math.min(D.clientHeight, B.clientHeight);  
        }  
    }  
	function autoSizeChatWindow(){
//	if(window.innerHeight!= undefined){  
//        return window.innerHeight;  
//    }  
//    else{  
//        var B= document.body, D= document.documentElement;  
//        return Math.min(D.clientHeight, B.clientHeight);  
//    } 
		$(".im-main-content").height($(window).innerHeight() - $(".top").innerHeight());
		$('#scrollDiv').height($(window).innerHeight() - $(".top").innerHeight() - $(".im-edit-area").innerHeight() - 0);
		//document.write($('#scrollDiv').height());
		$("#navcontent").height($(window).innerHeight() - $(".top").innerHeight() - $("#sidenav").innerHeight() - 0);
		$(".content").height($(window).innerHeight() - $(".top").innerHeight() - $("#sidenav").innerHeight() - 0);
		$(".im-chat-window").height($(window).innerHeight() - $(".top").innerHeight()  - 0);
		//document.write($(".im-chat-window").height())
		$('#scrollDiv').scrollTop($('#scrollDiv')[0].scrollHeight);
		//$('.im-edit-area').offset().top
		//document.write($(".top").height());
		//document.write($(window).innerHeight());
		//document.write($('#scrollDiv').outerHeight());
		//document.write($('.im-edit-area').outerHeight(true));
		//document.write($('#scrollDiv').offset().top)
		//document.write($('.im-edit-area').offsetParent.tagName);
		$('.im-edit-area').css({"top":$(".top").innerHeight()+$("#scrollDiv").innerHeight()-60+"px"});
			//$('.im-edit-area').css({"top":$('#scrollDiv').innerHeight()+$(".top").innerHeight()+"px"});
		
	
		//document.write($('.im-edit-area').offset().top);
	}
//统计字数
function check (str) {
	var num = [0, 50];
	for (var i=0; i<str.length; i++) {
		//字符串不是中文时
		if (str.charCodeAt(i) >= 0 && str.charCodeAt(i) <= 255){
			num[0] = num[0] + 0.5;//当前字数增加0.5个
			num[1] = num[1] + 0.5;//最大输入字数增加0.5个
		} else {//字符串是中文时
			num[0]++;//当前字数增加1个
		}
	}
	return num;
}
//表情
 function buildFace(){
	 var facepic;
	for(var i=1; i<36;i++){
		if(facepic){
			facepic +='<img src="/Home/images/OnLineTalk/Extracted/'+i+'.gif">';
		}else{
			facepic ='<img src="/Home/images/OnLineTalk/Extracted/'+i+'.gif">';
		}
	}
	return facepic;
 }
 //decode
	var REGX_HTML_DECODE = /&\w+;|&#(\d+);/g;
    var HTML_DECODE = {
        "&lt;" : "<",
        "&gt;" : ">",
        "&amp;" : "&",
        "&nbsp;": " ",
        "&quot;": "\"",
        "©": ""
    };
	function decodeHtml(s){
        s = (s != "undefined") ? s : this.toString();
        return (typeof s != "string") ? s :
            s.replace(REGX_HTML_DECODE,
                      function($0, $1){
                          var c = HTML_DECODE[$0];
                          if(c == "undefined"){
                              // Maybe is Entity Number
                              if(!isNaN($1)){
                                  c = String.fromCharCode(($1 == 160) ? 32:$1);
                              }else{
                                  c = $0;
                              }
                          }				
                          return c;
                      });
    };
//过滤
	function filterHtml(content){
		var safeContent,regstr;
		//alert(content);
		if(content){
			regstr=[
		
			/(&nbsp;|&amp;nbsp;)*/g,	
			
			/(&lt;(\/)*|<(\/)*)(\s*)script(&gt;|>)/g,
			///(&lt;|<)(.*)(&gt;|>)/g,		
			];
			for(var key in regstr){
				//alert(regstr[key]);	
				safeContent = content.replace(regstr[key],"");	
				//alert(safeContent);		
			}
		}
		return safeContent;
	}

//添加留言
	function checkTime(i){
	if (i<10){
		i="0" + i;
		}
	  return i;
	}	
	function addMsg(msgPic,msgName,msgTime,msgContent,typeid){
			//alert(typeid);
			msgContent=decodeHtml(filterHtml(msgContent));
			//alert(msgContent);
			var msgStr,msgType;
			var addTime = new Date(parseInt(msgTime)*1000);		
			addTime =checkTime(addTime.getHours())+':'+checkTime(addTime.getMinutes())+':'+checkTime(addTime.getSeconds());
			//alert(typeid);
			if(typeid ==0){
				msgType ="im-others";
			}else{
				msgType ="im-me";
				msgPic='/Home/images/OnLineTalk/wu.png';
			}
	
			if((msgPic==null || msgPic=="") && typeid ==0){
				
				msgPic='/Home/images/OnLineTalk/default-user-60-60.png';			
			}
	
			msgStr='<div class="im-item '+msgType+'">';
			msgStr+='<div class="im-message clearfix">';
			msgStr+='<div class="im-user-area"><a href="#" class="im-user-pic">';
			//头像
			msgStr+='<img alt="gj515" src="'+msgPic+'" class="userPic" border="0" > ';
			msgStr+='<img alt="" src="/Home/images/OnLineTalk/cap48.png" class="im-user-pic-cap" border="0" /></a></div>';
			msgStr+='<div class="im-message-detail">';
			msgStr+='<table class="im-message-table" border="0" cellpadding="0" cellspacing="0">';
			msgStr+='<tbody><tr><td class="lt"></td><td class="tt"></td><td class="rt"></td></tr>';
			msgStr+='<tr><td class="lm"><span></span></td><td class="mm"><div class="im-message-title">';
			msgStr+='<p class="im-message-owner">';
			//用户名
			msgStr+='<span class="im-txt-bold">'+msgName+'</span></p>';
			//时间
			msgStr+='<span class="im-send-time">'+addTime+'</span></div>';
			msgStr+='<div class="im-message-content">';
			msgStr+='<p style="font-family: 宋体; color: rgb(0, 0, 0);">';
			//留言
			msgStr+=msgContent;
			msgStr+='</p></div></td><td class="rm"><span></span></td></tr>';
			msgStr+='<tr><td class="lb"></td><td class="bm"></td><td class="rb"></td></tr>';
			msgStr+='</tbody></table></div></div></div>';
								
			return msgStr;
	}
//发消息
	function sendMsg(){
		
		var sendContent;
			sendContent = $("#text_in").html()
			sendContent = filterHtml(sendContent);
			if(sendContent =="" ){
				$("#msgError").show().html('请输入内容！').delay(1000).fadeOut(400);
				$("#text_in").html('');
				return false;
			}else{
				$("#msgError").html('');
			}
			$.ajax({url:"/OnLineTalk/saveMsg",type:"post",data:{content:sendContent},success:function(data){
	
				if(data["state"]){	
					pc_count++;
					pc_time=data['addtime'];	
					var newMsg = addMsg(user_image,user_name,data['addtime'],data['content'],data['msgtype']);				
					$(".im-chat-list").append(newMsg);	
					$('#scrollDiv').scrollTop($('#scrollDiv')[0].scrollHeight);
					$("#text_in").html('');
					$("#msgError").show().html('发送成功').delay(1000).fadeOut(400);										
				}else{
					$("#msgError").show().html('发送失败！').delay(1000).fadeOut(400);
				}
			}});	
	}
//读取消息
	function getMsg(count,time){
		//alert("hello");
		$.ajax({url:"/OnLineTalk/getMsg/rnd/"+Math.random(),type:"post",data:{gettime:time,getcount:count},success:function(data){
				
				if(data !='0'){	
				//alert('hello');	
					message.clear();
					message.show();
					pc_count=data['getcount'];
					pc_time=data['gettime'];
					//alert(pc_count);
					for(var key in data){			
						if(typeof(data[key])=="object"){		
						var newMsg =addMsg(data[key]['image'],data[key]['name'],data[key]['addtime'],data[key]['content'],data[key]['msgtype']);						
						$(".im-chat-list").append(newMsg);	
						}
					}
					autoSizeChatWindow();	
					$('#scrollDiv').scrollTop($('#scrollDiv')[0].scrollHeight);		
				}
		}});
	}

//开始
$(function(){
//新消息提示
	$(document).click(function(){
		message.clear();
	});

	
//初始位置	
	autoSizeChatWindow();
	//$('#scrollDiv').scrollTop($('#scrollDiv')[0].scrollHeight);
//窗口缩放	
	 $(window).resize(function () {
          autoSizeChatWindow();
      });
//加载表情
	$("#faceimage").html(buildFace());	 
	$("body").click(function(){
		if($("#expressionButton").hasClass("face_border")){
			$("#faceimage").hide(200);
			$("#expressionButton").removeClass("face_border");
		}
	}); 
	$("#expressionButton").click(function(event){		
		event.stopPropagation();
		$(this).addClass("face_border");
		var btn_face =$("#faceimage");
		if(btn_face.is(":visible")){
			btn_face.hide(200);
			$(this).addClass("face_border");
		}else{
			btn_face.show(200);
		}
	});
	$("#faceimage img").click(function(){
		$(this).clone().appendTo($("#text_in"));
		$("#faceimage").hide(200);
		$("#expressionButton").removeClass("face_border");
	});
	  //alert(pc_count);
	setInterval("getMsg(pc_count,pc_time)",5000); 
	
	
//切换效果	
	$(".navc-content:first").show();
	$(".side-nav-item:first").addClass("current");
	$(".side-nav-item").hover(function(){
		$(".navc-content").hide().eq($(".side-nav-item").removeClass("current").index($(this).addClass("current"))).show();
	});	
//订单
$(".tabcontent").hide().eq(0).show();
$(".tabmenu").click(function(){
	if($(this).next("div.tabcontent").is(":visible")){
		$(this).next("div.tabcontent").hide(200).siblings("div.tabcontent").show(200);
	}else{
		$(this).next("div.tabcontent").show(200).siblings("div.tabcontent").hide(200);
	}
	});			
//常见问题			
	$(".intro-bar").eq(0).children("div").addClass("triangle-open");		
	$("div.detail").hide().eq(0).show();
	$(".intro-bar").click(function(){
		if($(this).children("div").hasClass("triangle-open")){
			$(this).children("div").removeClass("triangle-open").addClass("triangle-close");
			$(this).siblings("div.intro-bar").children("div").removeClass("triangle-open").addClass("triangle-close");
			$(this).next().hide().siblings("div.detail").hide();
		}else{
			$(this).children("div").removeClass("triangle-close").addClass("triangle-open");
			$(this).siblings("div.intro-bar").children("div").removeClass("triangle-open").addClass("triangle-close");
			$(this).next().show().siblings("div.detail").hide();
		}
		
	});
//提交信息
	$("body").delegate("#sendMsg","click",function(){
		sendMsg();	
	});	
	$(document).keydown(function(event){ 
		var e = e || event,
		keycode = e.which || e.keyCode;
		if (keycode==13) {
			sendMsg();
		}
	});
	
//读取


// 滑动效果

var $liCur = $("#sidenav li.current"),
	curP = $liCur.position().left,
	curW = $liCur.outerWidth(true),
	$slider = $(".tab_arrow"),
	$navBox = $("#sidenav");
	$targetEle = $("#sidenav  li a"),
	$slider.animate({
	"left":curP,
	"width":curW
	});
	$targetEle.mouseenter(function () {
		var $_parent = $(this).parent(),
		_width = $_parent.outerWidth(true),
		posL = $_parent.position().left;
		$slider.stop(true, true).animate({
			"left":posL,
			"width":_width
			}, "fast");
	});
//	$navBox.mouseleave(function (cur, wid) {
//		cur = curP;
//		wid = curW;
//		$slider.stop(true, true).animate({
//		"left":cur,
//		"width":wid
//		}, "fast");
//	});
//表情

//字数
	$( '#text_in' ).bind('keyup', function () {
		var content = $(this).html();
		var lengths = check(content);  //调用check函数取得当前字数

		//最大允许输入50个字
		if (lengths[0] >= 50 && unbind ==0) {
			$(this).html(content.substring(0, Math.ceil(lengths[1])));
		}

		var num = 50 - Math.ceil(lengths[0]);
		var msg = num < 0 ? 0 : num;
		//当前字数同步到显示提示
		$( '#font-num' ).html( msg );
	} );
				
});

		

